<?php
session_start();
if ($_SERVER["REQUEST_METHOD"] == "POST") {
    $row = (int)$_POST["row"];
    $col = (int)$_POST["col"];
    $player = (int)$_POST["player"];

    // 更新棋盘状态
    $_SESSION['board'][$row][$col] = $player;

    // 检查是否有玩家获胜
    $winner = checkWinner($_SESSION['board'], $row, $col, $player);
    if ($winner) {
        $response = [
            'success' => true,
            'winner' => $winner,
            'draw' => false
        ];
    } else {
        // 检查是否平局
        if (isDraw($_SESSION['board'])) {
            $response = [
                'success' => true,
                'winner' => null,
                'draw' => true
            ];
        } else {
            $response = [
                'success' => true,
                'winner' => null,
                'draw' => false
            ];
        }
    }

    header('Content-Type: application/json');
    echo json_encode($response);
}

function checkWinner($board, $row, $col, $player) {
    $directions = [
        [[-1, 0], [1, 0]], // 水平方向
        [[0, -1], [0, 1]], // 垂直方向
        [[-1, -1], [1, 1]], // 正对角线方向
        [[-1, 1], [1, -1]] // 反对角线方向
    ];

    foreach ($directions as $direction) {
        $count = 1;
        foreach ($direction as $offset) {
            $r = $row;
            $c = $col;
            while (true) {
                $r += $offset[0];
                $c += $offset[1];
                if ($r < 0 || $r >= 15 || $c < 0 || $c >= 15 || $board[$r][$c] != $player) {
                    break;
                }
                $count++;
            }
        }
        if ($count >= 5) {
            return $player;
        }
    }
    return null;
}

function isDraw($board) {
    foreach ($board as $row) {
        foreach ($row as $cell) {
            if ($cell === 0) {
                return false;
            }
        }
    }
    return true;
}
?>